#-*- coding = utf-8 -*-
#@Time : 21-2-23 下午2:49
#@Author : wei
#@File : sqider4.py
#@Software: PyCharm


from bs4 import BeautifulSoup
import urllib.request,urllib.error
import re
import pymysql


def main():
    baseurl = "https://movie.douban.com/top250?start="
    #savepath = 'movie.db'
    datalist = getData(baseurl)
    #getData(baseurl)
    saveData2DB(datalist)
    #askURL(baseurl)

findLink = re.compile(r'<a href="(.*?)">')
findImgSrc = re.compile(r'<img.*?src="(.*?)"',re.S)
findTitle = re.compile(r'<span class="title">(.*)</span>')
findRate = re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>')
findJudge = re.compile(r'<span>(\d*)人评价</span>')
findInq = re.compile(r'<span class="inq">(.*?)</span>')
findBd = re.compile(r'<p class="">(.*?)</p>',re.S)

#爬取网页
def getData(baseurl):
    datalist = []
    for i in range(0,10):
        url = baseurl + str(i*25)
        html = askURL(url)
        soup = BeautifulSoup(html,'html.parser')
        for item in soup.find_all('div',class_='item'):
            item = str(item)
            #print(item)
            #break
            data = []
            link = re.findall(findLink,item)[0]
            data.append(link)
            imgSrc = re.findall(findImgSrc,item)[0]
            data.append(imgSrc)
            titles = re.findall(findTitle,item)
            if len(titles) == 2:
                ctitle = titles[0]
                data.append(ctitle)
                otitle = titles[1].replace('/','')
                data.append(otitle)
            else:
                data.append(titles[0])
                data.append(' ')
            rate = re.findall(findRate,item)[0]
            # rate = float(rate)
            data.append(rate)
            judgeNum = re.findall(findJudge,item)[0]
            # judgeNum = int(judgeNum)
            data.append(judgeNum)
            inq = re.findall(findInq,item)
            if len(inq) != 0:

                inq = inq[0].replace('。','')
                data.append(inq)
            else:
                data.append(' ')
            bd = re.findall(findBd,item)[0]
            bd = re.sub('<br(\s+)?>(\s+)?','',bd)
            bd = re.sub('</br(\s+)?>(\s+)?', '', bd)
            bd = re.sub('/',' ',bd)
            bd = bd.strip()
            data.append(bd)
            datalist.append(data)
    # print(datalist)
    # print('*'*20)
    return datalist

#得到指定一个URL的网页内容
def askURL(url):
    html = ''
    head = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:85.0) Gecko/20100101 Firefox/85.0'}
    request = urllib.request.Request(url,headers=head)
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode('utf-8')
        #print(html)
    except urllib.error.URLError as e:
        if hasattr(e,'code'):
            print(e.code)
        if hasattr(e,'reason'):
            print(e.reason)
    return html

#保存数据到mysql
def saveData2DB(datalist):
    init_db()
    db = pymysql.connect(host = 'localhost',user='root',password='010108',port=3306,db='movie')
    cursor = db.cursor()
    for data in datalist:
        #用replace into插入信息，避免爬取重复数据
        sql = '''replace into movie250(
              info_link, img_link, cname, oname, rate, judge_number, instroduction, info) values (%s,%s,%s,%s,%s,%s,%s,%s)'''
        try:
            cursor.execute(sql,data)
            db.commit()
            print('插入表成功')
        except Exception as e:
            db.rollback()
            print('插入表失败case:%s'%e)

    cursor.close()
    db.close()
    print('save...')

#连接mysql,建表
def init_db():
    db = pymysql.connect(host = 'localhost',user='root',password='010108',port=3306,db='movie')
    cursor = db.cursor()
    cursor.execute('drop table if exists movie250')
    sql='''create table movie250(
            id integer primary key auto_increment,
            info_link text,
            img_link text,
            cname varchar(100),
            oname varchar(100),
            rate numeric(10,1),
            judge_number numeric,
            instroduction text,
            info text)
            default character set = utf8;'''
    try:
        cursor.execute(sql)
        print('建表成功')
    except Exception as e:
        print('建表失败case:%s'%e)
    finally:
        #关闭游标连接
        cursor.close()
        # 关闭数据库连接
        db.close()


if __name__ == '__main__':
    main()
    print('爬取完毕')

